import { defineStore } from 'pinia'
import { getPastMedicalInfoById, editPastMedicalInfo, createPastMedicalInfo } from '@/service/api/healthRecords'

export interface PastMedicalInfoData {
  id: string|undefined
  idNumber: string
  recordid: string
  name: string
  note: string
}

// 扁平化的表单数据结构，用于表单绑定
export interface FormData {
  // 基本信息
  id: string
  idNumber: string
  recordid: string
  name: string
  visitTime: string
  visitTimeImages?: string[]
  
  // 诊断信息
  chiefComplaint: string
  chiefComplaintImages?: string[]
  diseaseName: string
  disease: string
  diseaseId: string | number
  diagnosisItems: Array<{
    diseaseName: string
    occupation?: string | number  // 职业
    diagnosisResult: string
    diagnosisResultImages: string[]
    diagnosisBasis: string
    diagnosisBasisImages: string[]
  }>
  
  // 就诊机构
  hospital: string
  hospitalImages?: string[]
  department: string
  departmentImages?: string[]
  dept: string
  project: string
  bedNumber: string
  
  // 专科评估
  specialistAssessment: string
  specialistAssessmentImages?: string[]
  
  // 手术史
  surgeryItems: Array<{
    title: string
    description: string
    images: string[]
  }>
  
  // 过敏史
  allergyItems: Array<{
    title: string
    description: string
    images: string[]
  }>
  
  // 预防接种与筛查计划
  vaccinationItems: Array<{
    title: string
    description: string
    images: string[]
  }>
  screeningItems: Array<{
    title: string
    description: string
    images: string[]
  }>
  screeningTime: string
  screeningTimeImages?: string[]
  screeningResults: string
  screeningResultsImages?: string[]
  
  // 周期性健康检查计划
  periodicHealthCheckItems: Array<{
    title: string
    description: string
    images: string[]
  }>
  
  // 生活方式与习惯改善计划
  lifestyleItems: Array<{
    title: string
    description: string
    images: string[]
  }>
  
  // 是否收案
  admissionItems: Array<{
    title: string
    description: string
    images: string[]
  }>
  
  // 措施模块
  homeCareRecords: Array<{
    title: string
    description: string
    images: string[]
  }>
  
  // 评价模块
  guardianEvaluations: Array<{
    content: string
    satisfaction: number
    details: {
      title: string
      description: string
      images: string[]
    }
  }>
  staffEvaluations: Array<{
    title: string
    description: string
    images: string[]
  }>
  institutionEvaluations: Array<{
    title: string
    description: string
    images: string[]
  }>
  
  // 反馈模块
  feedbackItems: Array<{
    title: string
    description: string
    images: string[]
  }>
  
  // 过敏防治
  allergyPrevention: string
  allergyPreventionImages?: string[]
  
  // 治疗计划
  prescription: string
  prescriptionImages?: string[]
  occupation?: string | number  // 职业
  dispositionItems: Array<{
    title: string
    description: string
    images: string[]
  }>
  healthEducationItems: Array<{
    title: string
    description: string
    images: string[]
  }>
  
  // 用药记录
  medicationRecords?: Array<{
    drugName: string           // 药物名称
    medicationMethod: string   // 用药方法
    dosage: string            // 用药剂量
    medicationFrequency: string // 用药频率
    medicationTime: string    // 用药时长
    effect: string           // 用药效果
  }>
  
  
  // 健康需求属性优化评估
  healthDemandAttributeOptimization?: {
    medicalAttribute: {
      proportion: number
      description: string
      images: string[]
    }
    healthAttribute: {
      proportion: number
      description: string
      images: string[]
    }
    rehabilitationAttribute: {
      proportion: number
      description: string
      images: string[]
    }
    careAttribute: {
      proportion: number
      description: string
      images: string[]
    }
    additionalAttributes: Array<{
      name: string
      proportion: number
      description: string
      images: string[]
    }>
    historicalAssessments: Array<{
      date: string
      assessment: string
    }>
    [key: string]: any  // 添加索引签名以支持动态访问
  }
  
  // 复杂嵌套数据（用于 sub-form 页面）
  comprehensiveHealthAssessment?: {
    // 1. 疾病与病症
    diseaseSymptoms: {
      description: string
      images: string[]
      newItems: Array<{ title: string; description: string; images: string[] }>
    }
    // 2. 整体健康状况
    generalHealthStatus: {
      description: string
      images: string[]
      newItems: Array<{ title: string; description: string; images: string[] }>
    }
    // 3. 体格检查与生理功能
    physicalExamination: {
      description: string
      images: string[]
      newItems: Array<{ title: string; description: string; images: string[] }>
      // 器官检查
      organExamination: {
        description: string
        images: string[]
        newItems: Array<{ title: string; description: string; images: string[] }>
      }
      // 专项检查
      specialExamination: {
        description: string
        images: string[]
        newItems: Array<{ title: string; description: string; images: string[] }>
      }
      // 辅助检查
      auxiliaryExamination: {
        description: string
        images: string[]
        newItems: Array<{ title: string; description: string; images: string[] }>
        // 实验室检查
        laboratoryExamination: {
          description: string
          images: string[]
        }
        // 影像学检查
        imagingExamination: {
          description: string
          images: string[]
        }
        // 内窥镜检查
        endoscopicExamination: {
          description: string
          images: string[]
        }
        // 电生理检查
        electrophysiologicalExamination: {
          description: string
          images: string[]
        }
        // 病理学检查
        pathologicalExamination: {
          description: string
          images: string[]
        }
      }
    }
    // 4. 自理能力
    selfCareAbility: {
      description: string
      images: string[]
      newItems: Array<{ title: string; description: string; images: string[] }>
    }
    // 5. 并发症与风险
    complicationsAndRisks: {
      description: string
      images: string[]
      newItems: Array<{ title: string; description: string; images: string[] }>
    }
  }
}

export interface MedicalRecordData {
  id: string
  idNumber: string
  recordid: string
  name: string
  note: {
    visitTime: string
    diagnosis: {
      result: string
      basis: string
    }
    medicalInstitution: {
      hospital: string
      department: string
      dept: string
      project: string
      bedNumber: string
    }
    chiefComplaint: string
    comprehensiveHealthAssessment: {
      // 1. 疾病与病症
      diseaseSymptoms: {
        description: string
        images: string[]
        newItems: Array<{ title: string; description: string; images: string[] }>
      }
      // 2. 整体健康状况
      generalHealthStatus: {
        description: string
        images: string[]
        newItems: Array<{ title: string; description: string; images: string[] }>
      }
      // 3. 体格检查与生理功能
      physicalExamination: {
        description: string
        images: string[]
        newItems: Array<{ title: string; description: string; images: string[] }>
        // 器官检查
        organExamination: {
          description: string
          images: string[]
          newItems: Array<{ title: string; description: string; images: string[] }>
        }
        // 专项检查
        specialExamination: {
          description: string
          images: string[]
          newItems: Array<{ title: string; description: string; images: string[] }>
        }
        // 辅助检查
        auxiliaryExamination: {
          description: string
          images: string[]
          newItems: Array<{ title: string; description: string; images: string[] }>
          // 实验室检查
          laboratoryExamination: {
            description: string
            images: string[]
          }
          // 影像学检查
          imagingExamination: {
            description: string
            images: string[]
          }
          // 内窥镜检查
          endoscopicExamination: {
            description: string
            images: string[]
          }
          // 电生理检查
          electrophysiologicalExamination: {
            description: string
            images: string[]
          }
          // 病理学检查
          pathologicalExamination: {
            description: string
            images: string[]
          }
        }
      }
      // 4. 自理能力
      selfCareAbility: {
        description: string
        images: string[]
        newItems: Array<{ title: string; description: string; images: string[] }>
      }
      // 5. 并发症与风险
      complicationsAndRisks: {
        description: string
        images: string[]
        newItems: Array<{ title: string; description: string; images: string[] }>
      }
    }
    specialistAssessment: string
    treatmentPlan: {
      prescription: string
      disposition: string
      healthEducation: string
    }
    surgery: {
      name: string
      history: string
      time: string
      hospital: string
    }
    allergies: {
      medication: string
      history: string
      food: string
      other: string
    }
    // 预防接种与筛查计划
    vaccinationScreening: {
      vaccinationRecord: string
      vaccineName: string
      vaccinationTime: string
      vaccinationUnit: string
      screeningRecord: string
      screeningItems: string
      screeningTime: string
      screeningResults: string
    }
    
    // 周期性健康检查计划
    periodicHealthCheck: {
      physicalExamPlan: string
      physicalExamTime: string
      physicalExamHospital: string
      physicalExamResults: string
      physicalExamAssessment: string
      physicalExamStatusAssessment: string
      physicalExamRecommendations: string
    }
    
    // 生活方式与习惯改善计划
    lifestyleImprovement: {
      nutritionIntake: string
      exerciseHabits: string
      smokingHabits: string
      drinkingHabits: string
    }
    
    // 过敏防治
    allergyPrevention: string
  }
}

export const useMedicalRecordStore = defineStore('medicalRecord', {
  state: (): { formData: FormData | null } => ({
    formData: null,
  }),

  getters: {
    getData: (state) => state.formData,
    getCurrentFormData: (state) => state.formData
  },

  actions: {
    /**
     * 初始化扁平化的表单数据
     */
    initializeFormData(data?: FormData) {
      this.formData = data || this.getDefaultFormData()
      console.log('initializeFormData----:', this.formData)
    },

    /**
     * 获取默认的表单数据
     */
    getDefaultFormData(): FormData {
      return {
        id: '',
        idNumber: '',
        recordid: '',
        name: '',
        visitTime: '',
        chiefComplaint: '',
        diseaseName: '',
        disease: '',
        diseaseId: '',
        diagnosisItems: [
          {
            diseaseName: '',
            occupation: 2,  // 默认值：专业技术人员（护士职业）
            diagnosisResult: '',
            diagnosisResultImages: [],
            diagnosisBasis: '',
            diagnosisBasisImages: []
          }
        ],
        hospital: '',
        department: '',
        dept: '',
        project: '',
        bedNumber: '',
        specialistAssessment: '',
        // 手术史
        surgeryItems: [],
        
        // 过敏史
        allergyItems: [],
        
        // 预防接种与筛查计划
        vaccinationItems: [],
        screeningItems: [],
        
        // 周期性健康检查计划
        periodicHealthCheckItems: [],
        
        // 生活方式与习惯改善计划
        lifestyleItems: [],
        
        // 是否收案
        admissionItems: [],
        
        // 措施模块
        homeCareRecords: [],
        
        // 评价模块
        guardianEvaluations: [],
        staffEvaluations: [],
        institutionEvaluations: [],
        
        // 反馈模块
        feedbackItems: [],
        
        // 过敏防治
        allergyPrevention: '',
        prescription: '',
        occupation: '',  // 职业
        dispositionItems: [],
        healthEducationItems: [],
    
    // 用药记录
    medicationRecords: [],
    
    
    // 健康需求属性优化评估
    healthDemandAttributeOptimization: {
      medicalAttribute: {
        proportion: 0,
        description: '',
        images: []
      },
      healthAttribute: {
        proportion: 0,
        description: '',
        images: []
      },
      rehabilitationAttribute: {
        proportion: 0,
        description: '',
        images: []
      },
      careAttribute: {
        proportion: 0,
        description: '',
        images: []
      },
      additionalAttributes: [],
      historicalAssessments: []
    },
    
    comprehensiveHealthAssessment: {
      // 1. 疾病与病症
      diseaseSymptoms: {
        description: '',
        images: [],
        newItems: []
      },
      // 2. 整体健康状况
      generalHealthStatus: {
        description: '',
        images: [],
        newItems: []
      },
      // 3. 体格检查与生理功能
      physicalExamination: {
        description: '',
        images: [],
        newItems: [],
        // 器官检查
        organExamination: {
          description: '',
          images: [],
          newItems: []
        },
        // 专项检查
        specialExamination: {
          description: '',
          images: [],
          newItems: []
        },
        // 辅助检查
        auxiliaryExamination: {
          description: '',
          images: [],
          newItems: [],
          // 实验室检查
          laboratoryExamination: {
            description: '',
            images: []
          },
          // 影像学检查
          imagingExamination: {
            description: '',
            images: []
          },
          // 内窥镜检查
          endoscopicExamination: {
            description: '',
            images: []
          },
          // 电生理检查
          electrophysiologicalExamination: {
            description: '',
            images: []
          },
          // 病理学检查
          pathologicalExamination: {
            description: '',
            images: []
          }
        }
      },
      // 4. 自理能力
      selfCareAbility: {
        description: '',
        images: [],
        newItems: []
      },
      // 5. 并发症与风险
      complicationsAndRisks: {
        description: '',
        images: [],
        newItems: []
      }
    }
      }
    },

    /**
     * 从嵌套的 note 对象转换为扁平化的表单数据
     */
    noteToFormData(note: any): FormData {
      return {
        id: '',
        idNumber: '',
        recordid: '',
        name: '',
        visitTime: note?.visitTime || '',
        chiefComplaint: note?.chiefComplaint || '',
        diseaseName: note?.diseaseName || '',
        diagnosisItems: note?.diagnosisItems || [
          {
            diseaseName: '',
            occupation: 2,  // 默认值：专业技术人员（护士职业）
            diagnosisResult: '',
            diagnosisResultImages: [],
            diagnosisBasis: '',
            diagnosisBasisImages: []
          }
        ],
        symptomsSummary: '',
        hospital: note?.medicalInstitution?.hospital || '',
        department: note?.medicalInstitution?.department || '',
        dept: note?.medicalInstitution?.dept || '',
        project: note?.medicalInstitution?.project || '',
        bedNumber: note?.medicalInstitution?.bedNumber || '',
        specialistAssessment: note?.specialistAssessment || '',
        // 手术史
        surgeryItems: note?.surgeryItems || [
          {
            title: '',
            description: '',
            images: []
          }
        ],
        
        // 过敏史
        allergyItems: note?.allergyItems || [
          {
            title: '',
            description: '',
            images: []
          }
        ],
        
        // 预防接种与筛查计划
        vaccinationItems: note?.vaccinationItems || [
          {
            title: '',
            description: '',
            images: []
          }
        ],
        screeningItems: note?.screeningItems || [
          {
            title: '',
            description: '',
            images: []
          }
        ],
        
        // 周期性健康检查计划
        periodicHealthCheckItems: note?.periodicHealthCheckItems || [
          {
            title: '',
            description: '',
            images: []
          }
        ],
        
        // 生活方式与习惯改善计划
        lifestyleItems: note?.lifestyleItems || [
          {
            title: '',
            description: '',
            images: []
          }
        ],
        
        // 过敏防治
        allergyPrevention: note?.allergyPrevention || '',
        prescription: note?.treatmentPlan?.prescription || '',
        dispositionItems: note?.treatmentPlan?.dispositionItems || [
          {
            title: '',
            description: '',
            images: []
          }
        ],
        healthEducationItems: note?.treatmentPlan?.healthEducationItems || [
          {
            title: '',
            description: '',
            images: []
          }
        ],
        comprehensiveHealthAssessment: note?.comprehensiveHealthAssessment || this.getDefaultFormData().comprehensiveHealthAssessment
      }
    },

    /**
     * 从扁平化的表单数据转换为嵌套的 note 对象
     */
    formDataToNote(formData: FormData): any {
      return {
        visitTime: formData.visitTime,
        diseaseName: formData.diseaseName,
        diagnosisItems: formData.diagnosisItems,
        medicalInstitution: {
          hospital: formData.hospital,
          department: formData.department,
          dept: formData.dept,
          project: formData.project,
          bedNumber: formData.bedNumber
        },
        chiefComplaint: formData.chiefComplaint,
        specialistAssessment: formData.specialistAssessment,
        // 手术史
        surgeryItems: formData.surgeryItems,
        
        // 过敏史
        allergyItems: formData.allergyItems,
        
        // 预防接种与筛查计划
        vaccinationItems: formData.vaccinationItems,
        screeningItems: formData.screeningItems,
        
        // 周期性健康检查计划
        periodicHealthCheckItems: formData.periodicHealthCheckItems,
        
        // 生活方式与习惯改善计划
        lifestyleItems: formData.lifestyleItems,
        
        // 过敏防治
        allergyPrevention: formData.allergyPrevention,
        comprehensiveHealthAssessment: formData.comprehensiveHealthAssessment,
        treatmentPlan: {
          prescription: formData.prescription,
          dispositionItems: formData.dispositionItems,
          healthEducationItems: formData.healthEducationItems
        }
      }
    },

    /**
     * 更新表单字段
     */
    updateField(field: string, value: any) {
      if (!this.formData) return
      
      const keys = field.split('.')
      let current: any = this.formData
      
      for (let i = 0; i < keys.length - 1; i++) {
        if (!current[keys[i]]) {
          current[keys[i]] = {}
        }
        current = current[keys[i]]
      }
      
      current[keys[keys.length - 1]] = value
    },

    /**
     * 添加新项目到数组字段
     */
    addNewItem(path: string, item: any) {
      if (!this.formData) return
      
      const keys = path.split('.')
      let current: any = this.formData
      
      for (const key of keys) {
        if (!current[key]) {
          current[key] = []
        }
        current = current[key]
      }
      
      if (Array.isArray(current)) {
        current.push(item)
      }
    },

    /**
     * 从数组字段中移除项目
     */
    removeNewItem(path: string, index: number) {
      if (!this.formData) return
      
      const keys = path.split('.')
      let current: any = this.formData
      
      for (const key of keys) {
        current = current[key]
      }
      
      if (Array.isArray(current)) {
        current.splice(index, 1)
      }
    },

    /**
     * 从既往病史记录加载数据
     * @param id 既往病史记录ID
     */
    async loadFromPastMedicalInfo(id: string) {
      try {
        console.log('开始加载既往病史数据，ID:', id)
        const response = await getPastMedicalInfoById(id)
        console.log('既往病史数据响应:', response)
        
        console.log('API 响应结构:', response)
        console.log('response.success:', response.success)
        console.log('response.success 的类型:', typeof response.success)
        
        if (response && response.success) {
          const pastMedicalInfo = response.success
          
          // 解析 note 字段
          let noteData = {}
          if (pastMedicalInfo.note) {
            try {
              noteData = JSON.parse(pastMedicalInfo.note)
            } catch (error) {
              console.warn('解析 note 字段失败，使用空对象:', error)
            }
          }
          
          // 转换为扁平化的表单数据
          const formData = this.noteToFormData(noteData)
          
          // 设置基本信息
          formData.id = pastMedicalInfo.id || ''
          formData.idNumber = pastMedicalInfo.idNumber || ''
          formData.recordid = pastMedicalInfo.recordid || ''
          formData.name = pastMedicalInfo.name || ''
          
          // 初始化表单数据
          this.initializeFormData(formData)
          
          console.log('数据加载完成:', this.formData)
          return { success: true, message: '数据加载成功' }
        } else {
          console.warn('API 响应格式不符合预期，尝试直接使用 response 作为数据')
          // 尝试直接使用 response 作为 pastMedicalInfo
          const pastMedicalInfo = response
          
          // 解析 note 字段
          let noteData = {}
          if (pastMedicalInfo.note) {
            try {
              noteData = JSON.parse(pastMedicalInfo.note)
            } catch (error) {
              console.warn('解析 note 字段失败，使用空对象:', error)
            }
          }
          
          // 转换为扁平化的表单数据
          const formData = this.noteToFormData(noteData)
          
          // 设置基本信息
          formData.id = pastMedicalInfo.id || ''
          formData.idNumber = pastMedicalInfo.idNumber || ''
          formData.recordid = pastMedicalInfo.recordid || ''
          formData.name = pastMedicalInfo.name || ''
          
          // 初始化表单数据
          this.initializeFormData(formData)
          
          console.log('数据加载完成 (备用方案):', this.formData)
          return { success: true, message: '数据加载成功 (备用方案)' }
        }
      } catch (error) {
        console.error('加载既往病史数据失败:', error)
        // 使用默认数据结构
        this.initializeFormData()
        return { success: false, message: `加载数据失败: ${error instanceof Error ? error.message : '未知错误'}` }
      }
    },

    /**
     * 保存数据到既往病史记录
     * @param id 既往病史记录ID（可选，用于编辑模式）
     */
    async saveToPastMedicalInfo(id?: string) {
      try {
        if (!this.formData) {
          throw new Error('没有可保存的数据')
        }

        console.log('开始保存数据到既往病史记录，ID:', id)
        console.log('要保存的表单数据:', this.formData)

        // 将扁平化的表单数据转换为嵌套的 note 对象
        const noteData = this.formDataToNote(this.formData)
        
        // 构建 PastMedicalInfoData 格式的数据
        const saveData: PastMedicalInfoData = {
          id: id || this.formData.id || undefined,
          idNumber: this.formData.idNumber,
          recordid: this.formData.recordid,
          name: this.formData.name,
          note: JSON.stringify(noteData)
        }

        console.log('构建的保存数据:', saveData)

        let response
        if (saveData.id) {
          // 编辑模式
          response = await editPastMedicalInfo(saveData)
        } else {
          // 新增模式
          response = await createPastMedicalInfo(saveData)
        }
        
        console.log('保存响应:', response)

        if (response && response.success) {
          console.log('数据保存成功')
          
          // 如果是新增模式，更新表单数据中的 ID
          if (!id && !this.formData.id && response.success.id) {
            this.updateField('id', response.success.id)
          }
          
          return { success: true, message: '数据保存成功', data: response.success }
        } else {
          throw new Error('保存响应格式异常')
        }
      } catch (error) {
        console.error('保存数据失败:', error)
        return { success: false, message: `保存失败: ${error instanceof Error ? error.message : '未知错误'}` }
      }
    }
  }
})
